<template>
  <div class="chapter-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">数据加载中...</div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">{{ error }}</div>


    <nut-tabs v-else v-model="value" title-scroll title-gutter="10" name="tabName">
      <nut-tab-pane v-for="item in data?.lists" :key="item.paneKey" :title="` ${item.title}`" :pane-key="item.paneKey">
        <!-- 章节单元格 -->
        <nut-cell desc-text-align="left" v-for="(cell, index) in getCellCount(item.paneKey)" :key="index"
          :desc="data.cellValues[item.paneKey][index]" @click="showActionSheet(item.paneKey, index)" />
      </nut-tab-pane>
    </nut-tabs>
    <!-- 自适应动作面板 -->
    <nut-action-sheet v-model:visible="show" :menu-items="getCurrentSummaries()" @choose="(item) => handleChoose(item)"
      class="custom-action-sheet"/>
      <!-- <template #default="{ item }">
        <nut-ellipsis direction="start" :content="item?.name"></nut-ellipsis>
      </template> -->
    <!-- </nut-action-sheet> -->
  </div>
</template>




<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import config from '../../config'


// 响应式状态
const value = ref('')
const show = ref(false)
const loading = ref(true)
const error = ref(null)
const activeCellInfo = ref({ paneKey: '', index: -1 })

// 数据容器
const data = ref({
  lists: [],            // 章节标签
  cellCounts: {},       // 单元格数量
  cellValues: {},       // 单元格基础值
  cellSummaries: {}     // 小结配置
})

// 计算属性 - 安全访问
const tabContainerWidth = computed(() => {
  const count = data.value?.lists?.length || 0  // 
  return count <= 3 ? '100%' : `${count * 120}px`
})
// 封装请求工具
const wxPromisify = (fn) => {
  return (config = {}) => {
    return new Promise((resolve, reject) => {
      config.success = resolve
      config.fail = reject
      fn(config)
    })
  }
}
// 数据获取
const fetchData = async () => {
  try {
    const wxRequest = wxPromisify(wx.request)
    const res = await wxRequest({
      url: `${config.apiUrl}/chapter/data-structure/1`,
      method: 'GET',
      header: { 'content-type': 'application/json' }
    })
    console.log('接口返回数据:', res.data)


    // 验证数据结构
    if (!res.data?.data) {
      throw new Error('接口返回数据为空')
    }

    const {
      tabs = [],
      cellCounts = {},
      cellValues = {},
      cellSummaries = {}
    } = res.data.data

    // 批量更新数据（字段名严格匹配）
    data.value = {
      lists: tabs,
      cellCounts,
      cellValues,
      cellSummaries
    }
    console.log('数据更新成功:', data.value.cellSummaries)
    // 设置默认激活标签
    if (data.value.lists.length > 0) {
      value.value = data.value.lists[0].paneKey
    }

  } catch (err) {
    console.error('数据加载失败:', err)
    error.value = '数据加载失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}

// 生命周期钩子
onMounted(async () => {
  await fetchData()
})
watch(
  () => data.value.lists,
  () => {
    console.log('标签列表更新:', data.value.lists)
  },
  (newLists) => {
    if (newLists.length > 0) {
      value.value = newLists[0].paneKey
    }
  },
  { immediate: true }
)
// 获取单元格数量
const getCellCount = (paneKey) => {
  const count = data.value.cellCounts[paneKey] || 0
  return Array.from({ length: count }, (_, i) => i + 1)
}

// 显示动作面板
const showActionSheet = (paneKey, index) => {
  activeCellInfo.value = { paneKey, index }
  show.value = true
}

// 获取当前小结菜单名称
const getCurrentSummaries = () => {
  const { paneKey, index } = activeCellInfo.value
  const array = ref([])
  data.value.cellSummaries[paneKey]?.[index].forEach(element => {
    console.log('当前小结菜单001:', element);
    array.value.push({
      id: element.id,
      name: element.name
    })
  });
  return array.value || []
}
// //获取小结菜单id
// const getCurrentSummaryId = () => {
//   const { paneKey, index } = activeCellInfo.value
//   return data.value.cellSummaries[paneKey]?.[index].id || []
// }
// 处理选项选择
const handleChoose = (item) => {
  console.log('选项选择2:', item.id)
  wx.navigateTo({
    url: `/pages/answer/index?id=${item.id}`,
  });
}
</script>


<style lang="scss">
.custom-action-sheet {
  .nut-action-sheet__item {
    text-align: left;

    .nut-action-sheet__item__text {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: block;
      max-width: 100%; // 可选：限制最大宽度
    }
  }
}
</style>